package com.example.ref;

import java.lang.reflect.Field;

public abstract class AbstractWhere<T> extends Statement 
{

	protected Generic<T> statement;
	protected Field[] fields;
	public AbstractWhere(Generic<T> statement, String field,int operator,Object value) throws Exception 
	{
		this.statement=statement;
		this.fields=statement.getInnerClass().getDeclaredFields();

		parseInternalValue();

		builder.append(retrieveWhereStatement(field, operator, value));
	}
	void parseInternalValue()
	{

		builder.append(statement.getBuilder().toString());

		builder.append(" WHERE ");
	}
	/**
	 * AND operator
	 * @param field name of field of the class
	 * @param operator a constant from RSQLiteOperator class
	 * @param value string value
	 * @throws Exception if field is not found
	 */
	protected void _and(String field,int operator,Object value) throws Exception
	{
		builder.append(" AND ");
		builder.append(retrieveWhereStatement(field, operator, value));
	}
	/**
	 * OR operator
	 * @param field name of field of the class
	 * @param operator a constant from RSQLiteOperator class
	 * @param value string value
	 * @throws Exception if field is not found
	 */
	protected void _or(String field,int operator,Object value) throws Exception
	{
		builder.append(" OR ");
		builder.append(retrieveWhereStatement(field, operator, value));
	}

	
	String retrieveWhereStatement(String field,int operation,Object value) throws Exception
	{
		RSQLiteDatabaseHelper.throwIfFieldDoesntExists(fields,field);
	
		StringBuilder builder= new StringBuilder();
		builder.append("[");
		builder.append(field.trim());
		builder.append("]");

		if(operation== RSQLiteOperator.EQUALS)
		{
			builder.append(" =");
			RSQLiteDatabaseHelper.appendWithOrWithoutQuotes(builder,value,value.getClass(),false);
		}
		else if(operation== RSQLiteOperator.GREATER_THAN)
		{
			builder.append(" >");
			RSQLiteDatabaseHelper.appendWithOrWithoutQuotes(builder,value,value.getClass(),false);
		}
		else if(operation== RSQLiteOperator.GREATER_OR_EQUALS_THAN_)
		{
			builder.append(" >=");
			RSQLiteDatabaseHelper.appendWithOrWithoutQuotes(builder,value,value.getClass(),false);
		}
		else if(operation== RSQLiteOperator.LESSER_THAN)
		{
			builder.append(" <");
			RSQLiteDatabaseHelper.appendWithOrWithoutQuotes(builder,value,value.getClass(),false);
		}
		else if(operation== RSQLiteOperator.LESSER_OR_EQUALS_THAN_)
		{
			builder.append(" <=");
			RSQLiteDatabaseHelper.appendWithOrWithoutQuotes(builder,value,value.getClass(),false);
		}
		else if(operation== RSQLiteOperator.LIKE)
		{
			builder.append(" LIKE '%");
			RSQLiteDatabaseHelper.appendWithOrWithoutQuotes(builder,value,value.getClass(),true);
			builder.append("%'");
		}
		return builder.toString();
	}
	

}
